package com.wanpinghui.supplier.addrbook;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextPaint;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.addrbook.adapter.AddressBooksAdapter;
import com.wanpinghui.supplier.common.BaseFragment;
import com.wanpinghui.supplier.oauth.LoginUtil;
import com.wanpinghui.supplier.object.HomePageActivity;
import com.wanpinghui.supplier.widgets.CountTextView;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.model.addrbook.AddrbookService;
import com.wanpinghui.wphlibrary.model.addrbook.bean.AddrbookBean;
import com.wanpinghui.wphlibrary.model.addrbook.bean.MobileListBean;
import com.wanpinghui.wphlibrary.model.addrbook.bean.MoblieBean;
import com.wanpinghui.wphlibrary.model.message.bean.RecentMsgBean;
import com.yunshl.yunshllibrary.recyclerview.BaseRecyclerViewAdapter;
import com.yunshl.yunshllibrary.recyclerview.OnItemClickListener;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import retrofit.callback.YRequestCallback;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/12/20
 ***/

@ContentView(R.layout.layout_fragment_addressbook)
public class AddrBookFragment extends BaseFragment {

    public static final int REQUEST_READ_CONTACTS = 110;

    @ViewInject(R.id.recyclerview)
    private SuperRecyclerView recyclerView;

    @ViewInject(R.id.srv_may_know)
    private SuperRecyclerView srv_may_know;

    @ViewInject(R.id.tv_mine_fans)
    private TextView tv_mine_fans;

    @ViewInject(R.id.tv_mine_tuozhan)
    private TextView tv_mine_tuozhan;

    @ViewInject(R.id.tv_open_addrbook)
    private TextView tv_open_addrbook;

    @ViewInject(R.id.ll_empty_view)
    private LinearLayout ll_empty_view;

    @ViewInject(R.id.ll_empty_view2)
    private LinearLayout ll_empty_view2;

    @ViewInject(R.id.ll_tv_null)
    private LinearLayout ll_tv_null;

    @ViewInject(R.id.tv_null)
    private TextView tv_null;

//    @ViewInject(R.id.tv_lookmore)
//    private TextView tv_lookmore;

    @ViewInject(R.id.tv_open_addrbook2)
    private TextView tv_open_addrbook2;

    private AddressBooksAdapter addressBooksAdapter;

    private AddressBooksAdapter maykownadapter;

    @ViewInject(R.id.ll_tuozhan)
    private ScrollView ll_tuozhan;

    @ViewInject(R.id.tv_may_know)
    private TextView tv_may_know;

    @ViewInject(R.id.fragment_tv_addrbook_count)
    private CountTextView fragment_tv_addrbook_count;

    private int currpage = 1;
    private int id = 1;
    private List<AddrbookBean> addrbookBeanList;

    private List<MoblieBean> moblieBeanList;

    private List<MoblieBean> maykownList;

    private View header;
    @Override
    public void init() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                ll_empty_view.setVisibility(View.VISIBLE);
            } else {
                readContact();
                ll_empty_view.setVisibility(View.GONE);
            }
        } else {
            readContact();
            ll_tv_null.setVisibility(View.VISIBLE);
        }
        addressBooksAdapter = new AddressBooksAdapter(getActivity());
        addressBooksAdapter.setFriends(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(addressBooksAdapter);

        header = LayoutInflater.from(getActivity()).inflate(R.layout.item_addrbook_header, srv_may_know, false);
        maykownadapter = new AddressBooksAdapter(getActivity());
        srv_may_know.setLayoutManager(new LinearLayoutManager(getActivity()));
        maykownadapter.setHeaderView(header);
        maykownadapter.setNewFriends(true);
        maykownadapter.setMayKnow(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            srv_may_know.setNestedScrollingEnabled(false);
        }
        srv_may_know.setAdapter(maykownadapter);

        tv_mine_fans.setSelected(true);
        addressBooksAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), CustomerInfoActivity.class);
                intent.putExtra("bean", addrbookBeanList.get(position));
                startActivity(intent);
            }
        });
        if (LoginUtil.isLogin()) {
            friends();
            unreadCount();
        }
        // addressBookList(currpage, BaseRecyclerViewAdapter.TYPE_PULL_REFRESH);
        getActivity().findViewById(R.id.iv_filter).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), AddfriendActivity.class));

            }
        });
        bindEvents();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (LoginUtil.isLogin()) {
            if (tv_mine_fans.isSelected()) {
                friends();
            } else {
                mobil_list(1, BaseRecyclerViewAdapter.TYPE_PULL_REFRESH, 6);
            }
            unreadCount();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (LoginUtil.isLogin()) {
                if (tv_mine_fans.isSelected()) {
                    friends();
                } else {
                    mobil_list(1, BaseRecyclerViewAdapter.TYPE_PULL_REFRESH, 6);
                }
                unreadCount();
            }
        }
    }

    private void unreadCount() {
        WPHSdk.getService(AddrbookService.class).unReadCount(new YRequestCallback<RecentMsgBean>() {
            @Override
            public void onSuccess(RecentMsgBean var1) {
                fragment_tv_addrbook_count.setCount(var1.getUn_read_count());
                ((HomePageActivity) getActivity()).setAddrbookCount(var1.getUn_read_count());
            }

            @Override
            public void onFailed(int var1, String message) {


            }

            @Override
            public void onException(Throwable var1) {

            }
        });
    }

    private void readContact() {
        if (LoginUtil.isLogin()) {
            WPHSdk.getService(AddrbookService.class).readContact(getActivity(), new YRequestCallback<ArrayList<HashMap<String, String>>>() {
                @Override
                public void onSuccess(ArrayList<HashMap<String, String>> var1) {
                    if (var1 != null) {
                        List<String> stringList = new ArrayList<>();
                        for (int i = 0; i < var1.size(); i++) {
                            stringList.add(var1.get(i).get("phone"));
                        }
                        updateMobilList(stringList);
                    }
                }

                @Override
                public void onFailed(int var1, String message) {

                }

                @Override
                public void onException(Throwable var1) {

                }
            });
        }
    }

    //更新上传通讯录
    private void updateMobilList(List<String> stringList) {
        if (stringList == null) return;
        if (stringList.size() == 0) return;
        WPHSdk.getService(AddrbookService.class).updateMobilList(stringList, new YRequestCallback<Object>() {
            @Override
            public void onSuccess(Object var1) {
                //    LogUtils.d("onSuccess",var1.toString());

            }

            @Override
            public void onFailed(int var1, String message) {
                //    LogUtils.d("onFailed",message);
            }

            @Override
            public void onException(Throwable var1) {
                //      LogUtils.d("onException",var1.toString());
            }
        });
    }

    //获取生意好友
    private void friends() {
        WPHSdk.getService(AddrbookService.class).friends(new YRequestCallback<MobileListBean>() {
            @Override
            public void onSuccess(MobileListBean var1) {
                recyclerView.setRefreshing(false);
                recyclerView.setLoadingMore(false);
                moblieBeanList = var1.getList();
                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
                    if (moblieBeanList != null && moblieBeanList.size() > 0) {
                        ll_empty_view.setVisibility(View.GONE);
                        ll_empty_view2.setVisibility(View.GONE);
                        ll_tv_null.setVisibility(View.GONE);
                        recyclerView.setVisibility(View.VISIBLE);
                        addressBooksAdapter.setDatas(moblieBeanList);
                    } else {
                        recyclerView.setVisibility(View.GONE);
                        ll_empty_view2.setVisibility(View.GONE);
                        ll_tv_null.setVisibility(View.VISIBLE);
                    }
                } else if (moblieBeanList != null && moblieBeanList.size() > 0) {
                    ll_empty_view.setVisibility(View.GONE);
                    ll_empty_view2.setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.VISIBLE);
                    addressBooksAdapter.setDatas(moblieBeanList);
                } else {
                    ll_empty_view2.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailed(int var1, String message) {
                recyclerView.setRefreshing(false);
                recyclerView.setLoadingMore(false);
                ll_tv_null.setVisibility(View.VISIBLE);
            }

            @Override
            public void onException(Throwable var1) {
                recyclerView.setRefreshing(false);
                recyclerView.setLoadingMore(false);
                ll_tv_null.setVisibility(View.VISIBLE);
            }
        });

    }

    private void bindEvents() {
        recyclerView.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currpage = 1;
                friends();
            }
        });
        tv_mine_tuozhan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextPaint paint = tv_mine_fans.getPaint();
                paint.setFakeBoldText(false);
                tv_mine_fans.setSelected(false);
                tv_mine_tuozhan.setSelected(true);
                TextPaint paint2 = tv_mine_tuozhan.getPaint();
                paint2.setFakeBoldText(true);
                recyclerView.setVisibility(View.GONE);
                currpage= 1;
                mobil_list(currpage, BaseRecyclerViewAdapter.TYPE_PULL_REFRESH, 10);

            }
        });
        tv_mine_fans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextPaint paint = tv_mine_fans.getPaint();
                paint.setFakeBoldText(true);
                tv_mine_fans.setSelected(true);
                tv_mine_tuozhan.setSelected(false);
                TextPaint paint2 = tv_mine_tuozhan.getPaint();
                paint2.setFakeBoldText(false);
                friends();
                srv_may_know.setVisibility(View.GONE);
                tv_null.setText("暂无生意好友");
            }
        });
        tv_open_addrbook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddrBookFragment.this.requestPermissions(new String[]{android.Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
            }
        });
        tv_open_addrbook2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddrBookFragment.this.requestPermissions(new String[]{android.Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
            }
        });
//        tv_lookmore.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (tv_lookmore.getText().toString().contains("查看更多")) {
//                    mobil_list(1, BaseRecyclerViewAdapter.TYPE_PULL_REFRESH, Integer.MAX_VALUE);
//                } else {
//                    mobil_list(1, BaseRecyclerViewAdapter.TYPE_PULL_REFRESH, 6);
//                }
//
//            }
//        });
        addressBooksAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), CustomerInfoActivity.class);
                intent.putExtra("bean", moblieBeanList.get(position));
                startActivity(intent);
            }
        });
        maykownadapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                position = position -1 ;
                if (maykownadapter.getDatas().get(position).getStatus_display().contains("已添加")) {
                    Intent intent = new Intent(getActivity(), CustomerInfoActivity.class);
                    intent.putExtra("bean", maykownadapter.getDatas().get(position));
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), StrangerInfoActivity.class);
                    intent.putExtra("status_display",maykownadapter.getDatas().get(position).getStatus_display());
                    intent.putExtra("bean", maykownadapter.getDatas().get(position));
                    startActivity(intent);
                }
            }
        });
        maykownadapter.setListener(new AddressBooksAdapter.setOnItemListener() {
            @Override
            public void setAddFriend(int position) {
                final MoblieBean bean = maykownadapter.getDatas().get(position-1);
                WPHSdk.getService(AddrbookService.class).addFriends(bean.getFollowed_id(), new YRequestCallback<Object>() {
                    @Override
                    public void onSuccess(Object var1) {
                        bean.setState(30);
                        bean.setStatus_display("等待认证");
                        maykownadapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        //showWarningText("添加失败");

                    }

                    @Override
                    public void onException(Throwable var1) {
                        var1.printStackTrace();

                    }
                });
            }

            @Override
            public void setAgreeFriend(int position) {

            }

            @Override
            public void setInvite(int position) {

            }
        });

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                ll_empty_view.setVisibility(View.GONE);
                ll_empty_view2.setVisibility(View.GONE);
                readContact();
                if (tv_mine_fans.isSelected()) {
                    if (moblieBeanList != null && moblieBeanList.size() > 0) {
                        recyclerView.setVisibility(View.VISIBLE);
                        ll_tv_null.setVisibility(View.GONE);
                    } else {
                        recyclerView.setVisibility(View.GONE);
                        ll_tv_null.setVisibility(View.VISIBLE);
                        tv_null.setText("暂无生意好友");
                    }
                } else {
                    if (maykownList != null && maykownList.size() > 0) {
                        recyclerView.setVisibility(View.GONE);
                        srv_may_know.setVisibility(View.VISIBLE);
                    } else {
                        srv_may_know.setVisibility(View.GONE);
                        ll_tv_null.setVisibility(View.VISIBLE);
                        tv_null.setText("暂无推荐好友");
                    }
                }
            }
        }

    }


    private void mobil_list(int page, final int type, int per_page) {
        //"page_type": 10    // 10 可能认识   20 通讯录(包括已邀请)
        WPHSdk.getService(AddrbookService.class).mobil_list(page, per_page, 10, new YRequestCallback<MobileListBean>() {
            @Override
            public void onSuccess(MobileListBean var1) {
                if (type == BaseRecyclerViewAdapter.TYPE_PULL_REFRESH) {
                    maykownList = var1.getList();
                    if (ll_empty_view.getVisibility() == View.GONE) {
                        if (maykownList != null && maykownList.size() > 0) {
                            if (maykownList.size() <= 6) {
                                //tv_lookmore.setVisibility(View.GONE);
                            }
                            tv_may_know.setVisibility(View.VISIBLE);
                            ll_tv_null.setVisibility(View.GONE);
                            srv_may_know.setVisibility(View.VISIBLE);
                            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                                ll_empty_view2.setVisibility(View.VISIBLE);
                                ll_empty_view.setVisibility(View.GONE);
                            } else {
                                ll_empty_view2.setVisibility(View.GONE);
                                ll_empty_view.setVisibility(View.GONE);
                            }
                        } else {
                            if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                                ll_empty_view.setVisibility(View.VISIBLE);
                                ll_empty_view2.setVisibility(View.GONE);
                                ll_tv_null.setVisibility(View.GONE);
                            } else {
                                ll_empty_view2.setVisibility(View.GONE);
                                ll_empty_view.setVisibility(View.GONE);
                                ll_tv_null.setVisibility(View.VISIBLE);
                            }
                            srv_may_know.setVisibility(View.GONE);

                        }
                    } else if (maykownList != null && maykownList.size() > 0) {
                        ll_empty_view.setVisibility(View.GONE);
                        ll_empty_view2.setVisibility(View.VISIBLE);
                        srv_may_know.setVisibility(View.VISIBLE);

                    } else {
                        ll_tv_null.setVisibility(View.GONE);
                        ll_empty_view2.setVisibility(View.GONE);
                        srv_may_know.setVisibility(View.GONE);
                    }
                } else {

                      srv_may_know.hideMoreProgress();
                    maykownList.addAll(var1.getList());
                }
                srv_may_know.setLoadingMore(false);
                maykownadapter.setDatas(maykownList);
                if (maykownadapter.getDatas().size() < var1.getTotal()) {
                    srv_may_know.setupMoreListener(new OnMoreListener() {
                        @Override
                        public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
                            srv_may_know.showMoreProgress();
                            currpage = currpage + 1;
                            mobil_list(currpage, BaseRecyclerViewAdapter.TYPE_PULL_MORE, 10);
                        }
                    }, 1);
                //    tv_lookmore.setText("查看更多");
                } else {
              //      tv_lookmore.setText("收起更多");
                    srv_may_know.removeMoreListener();
                }
                tv_null.setText("暂无推荐好友");

            }

            @Override
            public void onFailed(int var1, String message) {
                tv_null.setText("暂无推荐好友");
                //     ll_tv_null.setVisibility(View.VISIBLE);
            }

            @Override
            public void onException(Throwable var1) {
                var1.printStackTrace();
            }
        });

    }

}